package com.rtf.framework.web.mvc.config.session.source;

import com.rtf.framework.common.config.AppProperties;
import com.rtf.framework.common.config.AppSecureProperties;
import com.rtf.framework.common.json.JsonMapper;
import com.rtf.framework.common.util.UtilString;
import com.rtf.framework.web.mvc.config.secure.configurer.support.UrlAuthDetail;
import com.rtf.framework.web.mvc.config.session.source.springInterface.AppSessionRepository;
import com.google.api.client.util.Lists;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.session.MapSession;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration;
import org.springframework.session.data.redis.RedisFlushMode;
import org.springframework.session.data.redis.config.ConfigureNotifyKeyspaceEventsAction;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.SpringSessionRedisConnectionFactory;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;

import javax.servlet.ServletContext;
import java.util.List;
import java.util.concurrent.Executor;

import static com.rtf.framework.web.mvc.config.secure.AppSecureFilter.anon;

@Slf4j
@EnableScheduling
public class AppRedisHttpSessionConfiguration extends SpringHttpSessionConfiguration
		implements BeanClassLoaderAware, EmbeddedValueResolverAware,
		SchedulingConfigurer , InitializingBean {

	static final String DEFAULT_CLEANUP_CRON = "0 * * * * *";

	private Integer maxInactiveIntervalInSeconds = MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS;

	private String redisNamespace = AppRedisOperationsSessionRepository.DEFAULT_NAMESPACE;

	private RedisFlushMode redisFlushMode = RedisFlushMode.ON_SAVE;

	private String cleanupCron = DEFAULT_CLEANUP_CRON;

	private ConfigureRedisAction configureRedisAction = new ConfigureNotifyKeyspaceEventsAction();

	private RedisConnectionFactory redisConnectionFactory;

	private RedisSerializer<Object> defaultRedisSerializer;

	private ApplicationEventPublisher applicationEventPublisher;

	private Executor redisTaskExecutor;

	private Executor redisSubscriptionExecutor;

	private ClassLoader classLoader;

	private StringValueResolver embeddedValueResolver;

	@Autowired
	private AppProperties appProperties ;


	/**
	 * 不同url格式之间的分隔符
	 */
	public static final String URL_PATTERN_SPLITTER  = "," ;

	@Autowired
	protected AppSecureProperties appSecureProperties;

	private boolean enableAnonSession = false;

	private List<String> specialAnonUrl = Lists.newArrayList();

	private List<String> anonUrlList = Lists.newArrayList();

	private ServletContext servletContext;

	private CookieHttpSessionIdResolver defaultHttpSessionIdResolver = new CookieHttpSessionIdResolver();

	private HttpSessionIdResolver httpSessionIdResolver = this.defaultHttpSessionIdResolver;


	@Autowired(required = false)
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Autowired(required = false)
	@Override
	public void setHttpSessionIdResolver(HttpSessionIdResolver httpSessionIdResolver) {
		this.httpSessionIdResolver = httpSessionIdResolver;
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		this.maxInactiveIntervalInSeconds = appProperties.getSession().getTimeout() ;
		log.debug("session的配置信息->"+ JsonMapper.toJSONString( appProperties.getSession() ));

		AppSecureProperties.AuthConfig authConfig = appSecureProperties.getAuth() ;

		if( authConfig.getUrlAuths() != null && !authConfig.getUrlAuths().isEmpty() ){

			authConfig.getUrlAuths().stream().forEach( urlAuth -> {

				// 获取url指定的filter及参数
				List<UrlAuthDetail> urlAuthDetails = UrlAuthDetail.buildUrlAuthDetails( urlAuth ) ;

				// 需要认证的url
				List<String> urlPatterns = Splitter.on( URL_PATTERN_SPLITTER ).omitEmptyStrings().trimResults()
						.splitToList( urlAuth.getUrl() ) ;

				for ( String urlPattern : urlPatterns ) {
					// 针对 url 配置
					if (!anonUrlList.contains(urlPattern)) {

						urlAuthDetails.stream().forEach( urlAuthDetail -> {

							if (urlAuthDetail.appSecureFilter == anon){
								anonUrlList.add(urlPattern);
							}
						});
					}
				}
			});
		}

		//add by zhangzz 2020.08.19
		//为特殊URL增加两个默认
		String sAnnonUrl = appProperties.getSession().getSpecialAnonUrl();
		String specialAnonUrlCommon = "/api/user/**,/oauth2/login/**,/logout";
		if (UtilString.isEmpty(sAnnonUrl)){
			sAnnonUrl = specialAnonUrlCommon;
		}
		if (UtilString.isNotEmpty(sAnnonUrl)){
			sAnnonUrl = specialAnonUrlCommon + "," + sAnnonUrl;
			this.specialAnonUrl = Splitter.on( URL_PATTERN_SPLITTER ).omitEmptyStrings().trimResults()
					.splitToList( sAnnonUrl );
		}
		this.enableAnonSession = appProperties.getSession().isEnableAnonSession();
	}

	@Bean
	@Override
	public <S extends Session> AppSessionRepositoryFilter<? extends Session> springSessionRepositoryFilter(
			SessionRepository<S> sessionRepository) {
		AppSessionRepositoryFilter<S> sessionRepositoryFilter = new AppSessionRepositoryFilter<>(
				(AppSessionRepository) sessionRepository);
		sessionRepositoryFilter.setServletContextNew(this.servletContext);
		sessionRepositoryFilter.setHttpSessionIdResolverNew(this.httpSessionIdResolver);
		sessionRepositoryFilter.setEnableAnonSession(enableAnonSession);
		sessionRepositoryFilter.setAnonUrlList(anonUrlList);
		sessionRepositoryFilter.setSpecialAnonUrl(specialAnonUrl);
		return sessionRepositoryFilter;
	}

	@Bean
	public AppRedisOperationsSessionRepository sessionRepository(StringRedisTemplate stringRedisTemplate) {
		log.debug("初始化session加载类: {}" , AppRedisOperationsSessionRepository.class ); ;
		RedisTemplate<Object, Object> redisTemplate = createRedisTemplate();
		AppRedisOperationsSessionRepository sessionRepository = new AppRedisOperationsSessionRepository(appProperties,
				redisTemplate,appSecureProperties,stringRedisTemplate);
		sessionRepository.setApplicationEventPublisher(this.applicationEventPublisher);
		if (this.defaultRedisSerializer != null) {
			sessionRepository.setDefaultSerializer(this.defaultRedisSerializer);
		}
		sessionRepository
				.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds);
		if (StringUtils.hasText(this.redisNamespace)) {
			sessionRepository.setRedisKeyNamespace(this.redisNamespace);
		}
		sessionRepository.setRedisFlushMode(this.redisFlushMode);
		return sessionRepository;
	}

	@Bean
	public RedisMessageListenerContainer redisMessageListenerContainer() {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(this.redisConnectionFactory);
		if (this.redisTaskExecutor != null) {
			container.setTaskExecutor(this.redisTaskExecutor);
		}
		if (this.redisSubscriptionExecutor != null) {
			container.setSubscriptionExecutor(this.redisSubscriptionExecutor);
		}
//		container.addMessageListener(sessionRepository(),
//				Arrays.asList(new PatternTopic("__keyevent@*:del"),
//						new PatternTopic("__keyevent@*:expired")));
//		container.addMessageListener(sessionRepository(),
//				Collections.singletonList(new PatternTopic(
//						sessionRepository().getSessionCreatedChannelPrefix() + "*")));
		return container;
	}

	@Bean
	public InitializingBean enableRedisKeyspaceNotificationsInitializer() {
		return new EnableRedisKeyspaceNotificationsInitializer(
				this.redisConnectionFactory, this.configureRedisAction);
	}

	public void setMaxInactiveIntervalInSeconds(int maxInactiveIntervalInSeconds) {
		this.maxInactiveIntervalInSeconds = maxInactiveIntervalInSeconds;
	}

	public void setRedisNamespace(String namespace) {
		this.redisNamespace = namespace;
	}

	public void setRedisFlushMode(RedisFlushMode redisFlushMode) {
		Assert.notNull(redisFlushMode, "redisFlushMode cannot be null");
		this.redisFlushMode = redisFlushMode;
	}

	public void setCleanupCron(String cleanupCron) {
		this.cleanupCron = cleanupCron;
	}

	/**
	 * Sets the action to perform for configuring Redis.
	 *
	 * @param configureRedisAction the configureRedis to set. The default is
	 * {@link ConfigureNotifyKeyspaceEventsAction}.
	 */
	@Autowired(required = false)
	public void setConfigureRedisAction(ConfigureRedisAction configureRedisAction) {
		this.configureRedisAction = configureRedisAction;
	}

	@Autowired
	public void setRedisConnectionFactory(
			@SpringSessionRedisConnectionFactory ObjectProvider<RedisConnectionFactory> springSessionRedisConnectionFactory,
			ObjectProvider<RedisConnectionFactory> redisConnectionFactory) {
		RedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory
				.getIfAvailable();
		if (redisConnectionFactoryToUse == null) {
			redisConnectionFactoryToUse = redisConnectionFactory.getObject();
		}
		this.redisConnectionFactory = redisConnectionFactoryToUse;
	}

	@Autowired(required = false)
	@Qualifier("springSessionDefaultRedisSerializer")
	public void setDefaultRedisSerializer(
			RedisSerializer<Object> defaultRedisSerializer) {
		this.defaultRedisSerializer = defaultRedisSerializer;
	}

	@Autowired
	public void setApplicationEventPublisher(
			ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}

	@Autowired(required = false)
	@Qualifier("springSessionRedisTaskExecutor")
	public void setRedisTaskExecutor(Executor redisTaskExecutor) {
		this.redisTaskExecutor = redisTaskExecutor;
	}

	@Autowired(required = false)
	@Qualifier("springSessionRedisSubscriptionExecutor")
	public void setRedisSubscriptionExecutor(Executor redisSubscriptionExecutor) {
		this.redisSubscriptionExecutor = redisSubscriptionExecutor;
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		this.embeddedValueResolver = resolver;
	}

//	@Override
//	public void setImportMetadata(AnnotationMetadata importMetadata) {
//		Map<String, Object> attributeMap = importMetadata
//				.getAnnotationAttributes(EnableRedisHttpSession.class.getName());
//		AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
//		this.maxInactiveIntervalInSeconds = attributes
//				.getNumber("maxInactiveIntervalInSeconds");
//		String redisNamespaceValue = attributes.getString("redisNamespace");
//		if (StringUtils.hasText(redisNamespaceValue)) {
//			this.redisNamespace = this.embeddedValueResolver
//					.resolveStringValue(redisNamespaceValue);
//		}
//		this.redisFlushMode = attributes.getEnum("redisFlushMode");
//		String cleanupCron = attributes.getString("cleanupCron");
//		if (StringUtils.hasText(cleanupCron)) {
//			this.cleanupCron = cleanupCron;
//		}
//	}

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		// 使用redis的本身调度机制
//		taskRegistrar.addCronTask(() -> sessionRepository().cleanupExpiredSessions(),
//				this.cleanupCron);
	}

	private RedisTemplate<Object, Object> createRedisTemplate() {
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		if (this.defaultRedisSerializer != null) {
			redisTemplate.setDefaultSerializer(this.defaultRedisSerializer);
		}
		redisTemplate.setConnectionFactory(this.redisConnectionFactory);
		redisTemplate.setBeanClassLoader(this.classLoader);
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}

	/**
	 * Ensures that Redis is configured to send keyspace notifications. This is important
	 * to ensure that expiration and deletion of sessions trigger SessionDestroyedEvents.
	 * Without the SessionDestroyedEvent resources may not get cleaned up properly. For
	 * example, the mapping of the Session to WebSocket connections may not get cleaned
	 * up.
	 */
	static class EnableRedisKeyspaceNotificationsInitializer implements InitializingBean {

		private final RedisConnectionFactory connectionFactory;

		private ConfigureRedisAction configure;

		EnableRedisKeyspaceNotificationsInitializer(
				RedisConnectionFactory connectionFactory,
				ConfigureRedisAction configure) {
			this.connectionFactory = connectionFactory;
			this.configure = configure;
		}

		@Override
		public void afterPropertiesSet() throws Exception {
			if (this.configure == ConfigureRedisAction.NO_OP) {
				return;
			}
			RedisConnection connection = this.connectionFactory.getConnection();
			try {
				this.configure.configure(connection);
			}
			finally {
				try {
					connection.close();
				}
				catch (Exception ex) {
					LogFactory.getLog(getClass()).error("Error closing RedisConnection",
							ex);
				}
			}
		}

	}

}
